package com.verlet.servicehi;

import com.verlet.servicehi.entity.MessageObject;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author verlet
 * @date 2020/2/1
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("confirmCallback=" + "correlationData=" + correlationData);
            System.out.println("confirmCallback=" + "ack=" + ack + "; cause" + cause);
        }
    };

    public final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println("returnCallback=" + "message=" + message);
            System.out.println("returnCallback=" + "replyCode=" + replyCode + "; replyText=" + replyText);
            System.out.println("returnCallback=" + "exchange=" + exchange + "; routingKey=" + routingKey);
        }
    };

    public void send(String msg, Map<String, Object> properties) {
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        Message<String> message = MessageBuilder.createMessage(msg, messageHeaders);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend("test001.topic.exchange", "test001.hello", message, new CorrelationData(String.valueOf(msg.hashCode())));
    }

    public void send2(MessageObject msg) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend("test001.topic.exchange1", "test002.hello", msg, new CorrelationData(String.valueOf(msg.hashCode())));
    }

}
